﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;

namespace LiteExpress.Utilities
{
    public class ImageHelper
    {
        /// <summary>
        /// 压缩并缩小图片
        /// </summary>
        /// <param name="imagebytes">原图片字节数组</param>
        /// <param name="width">宽度</param>
        /// <param name="height">高度</param>
        /// <param name="quality">质量0-100</param>
        /// <returns>处理后的图片 可使用Convert.ToBase64String转为64字符串输出。
        /// 前台：src="data:image/png;base64,{base64string}"</returns>
        public static byte[] smallerImage(byte[] imagebytes, int maxwidth, int maxheight, long quality=50)
        {
            Image originalImg;
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream(imagebytes))
            {
                originalImg = Image.FromStream(ms);
                ms.Flush();
            }

            byte[] bytes;
            using (var ms = new MemoryStream())
            {
                ImageCodecInfo jgpEncoder = GetEncoder(ImageFormat.Png);

                EncoderParameters myEncoderParameters = new EncoderParameters(1);
                EncoderParameter myEncoderParameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                myEncoderParameters.Param[0] = myEncoderParameter;

                int width = maxwidth, height = maxheight;
                if (height < originalImg.Height * width / originalImg.Width)
                {
                    width = originalImg.Width * height / originalImg.Height;
                }
                else
                {
                    height = originalImg.Height * width / originalImg.Width;
                }

                var bitpic = new Bitmap(originalImg, width, height);

                bitpic.Save(ms, jgpEncoder, myEncoderParameters);
                ms.Position = 0;
                bytes = ms.ToArray();
            }
            return bytes;
        }

        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }
    }
}
